<template>
  <div class="login">
    <div class="content">
        <div class="left">
            <img src="@/assets/img/userLogin/bg.jpeg" alt="">
        </div>

        <div class="time">
           <h2>在线点餐系统</h2>  {{date+ '  '}}{{time}}
        </div>

        <div class="form">
            <a-form v-if="status === 1 && type == 1"
                    :model="loginForm"
                    ref="loginRef"
                    :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-item label="手机号" name="mobile">
                    <a-input v-model:value="loginForm.mobile" placeholder="请输入手机号" />
                </a-form-item>
                <a-form-item label="密码">
                    <a-input v-model:value="loginForm.password" placeholder="请输入密码" />
                </a-form-item>
                <a-form-item label="验证码">
                    <div class="code">
                        <a-input v-model:value="loginForm.captcha" placeholder="请输入验证码" />
                        <div class="captcha" @click="refreshCode">
                            <img :src="imgUrl" alt="">
                        </div>
                    </div>
                </a-form-item>
                <a-form-item label="登录方式" name="type">
                    <a-radio-group v-model:value="type">
                        <a-radio :value="1">密码登录</a-radio>
                        <a-radio :value="2">验证码登录</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                    <!--                    <img :src="imgUrl" alt="">-->
                    <a-button type="primary" @click.prevent="onSubmit">登录</a-button>
                    <a-button style="margin-left: 10px" @click="reset">重置</a-button>
                    <!--                  <a-button style="margin-left: 10px" @click="reset">用户注册</a-button>-->
                </a-form-item>
            </a-form>


            <!--       手机号+短信验证码登录表单         -->
            <a-form
                :model="codeForm"
                :rules="registerRules"
                ref="codeFormRef"
                v-if="status === 1 && type == 2"
                :label-col="labelCol"
                :wrapper-col="wrapperCol">
                <a-form-item label="手机号" name="mobile">
                    <a-input-search
                        v-model:value="codeForm.mobile"
                        placeholder="请输入手机号"
                        enter-button="获取验证码"
                        size="large"
                        :loading=codeLoading
                        @search="getLoginCode"
                    />
                </a-form-item>
                <a-form-item label="验证码" name="ssmCode ">
                    <a-input v-model:value="codeForm.ssmCode " placeholder="请输入验证码" />
                </a-form-item>

                <a-form-item label="登录方式" name="type">
                    <a-radio-group v-model:value="type">
                        <a-radio :value="1">密码登录</a-radio>
                        <a-radio :value="2">验证码登录</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                    <a-button type="primary" @click.prevent="codeLogin">登录</a-button>
                    <a-button style="margin-left: 10px" @click="resetCodeForm">重置</a-button>
                </a-form-item>
            </a-form>


            <!--       注册表单         -->
            <a-form
                :model="registerForm"
                :rules="registerRules"
                ref="registerRef"
                v-if="status === 2"
                :label-col="labelCol"
                :wrapper-col="wrapperCol">
<!--                <a-form-item label="邮箱" name="email">-->
<!--                    <a-input v-model:value="registerForm.email" placeholder="请输入邮箱" />-->
<!--                </a-form-item>-->
                <a-form-item label="手机号" name="mobile">
                    <a-input-search
                        v-model:value="registerForm.mobile"
                        placeholder="请输入手机号"
                        enter-button="获取验证码"
                        size="large"
                        :loading=codeLoading
                        @search="getCode"
                    />
                </a-form-item>
                <a-form-item label="验证码" name="checkCode ">
                    <a-input v-model:value="registerForm.checkCode " placeholder="请输入验证码" />
                </a-form-item>
                <a-form-item label="密码" name="password">
                    <a-input v-model:value="registerForm.password" placeholder="请输入密码" />
                </a-form-item>
                <a-form-item label="昵称" name="nickname">
                    <a-input v-model:value="registerForm.nickname" placeholder="请输入用户名" />
                </a-form-item>
                <a-form-item label="性别" name="sex">
                    <a-radio-group v-model:value="registerForm.sex">
                        <a-radio value="0">男</a-radio>
                        <a-radio value="1">女</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                    <a-button type="primary" @click.prevent="register">注册</a-button>
                    <a-button style="margin-left: 10px" @click="resetRegister">重置</a-button>
                </a-form-item>
            </a-form>

            <div class="bottom">
                <div v-if="status == 1">
                    <span style="color: #000">还没有账号? &nbsp;</span>
                    <span style="font-size: 18px; color: red" @click="toRegister">立即注册</span>
                </div>
                <div v-if="status === 2">
                    已有账号?
                    <span style="font-size: 18px; color: red" @click="toLogin">返回登录</span>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import {defineComponent, ref, UnwrapRef, reactive, toRefs, onMounted,  onUnmounted} from "vue";
import { dateFormat } from '../../untils/date.js'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {apiUserRegister, apiGetUserCode, apiGetUserImgCode, apiUserLogin, apiGetUserInfo} from "../../api";

export default defineComponent({
  name: "userLogin",
  components: {},
  setup() {
      const state = reactive({
          timeTimer: undefined,
          time: '',             // 当前时间
          date: '',             // 当前日期
          status: 1,            // 判断是注册还是登录
          codeLoading: false,
          imgUrl: '',
          type: 1,            // 判断是密码登录还是验证码登录
      })
    const registerRef = ref()
    const loginRef = ref()
      const codeFormRef = ref()
    const router = useRouter()
    const registerForm = reactive({
      // email: '',
      mobile: '',
      password: '',
      sex: '',
        nickname: '',
        checkCode: ''
    })
    const loginForm = reactive({
      mobile: '18939450951',
      password: 'lnb',
      captcha: '',
        type: 1
    })
      const codeForm = reactive({
          mobile: '18939450951',
          ssmCode: '',
          type: 2
      })


    // 自定义检验邮箱
    let checkEmail = async (rule, value) => {
      if (!value) {
        return Promise.reject('请输入邮箱');
      }
      if (/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请输入合法的邮箱');
      }
    }

    // 自定义检验手机号
    let checkMobile = (rule, value) => {
      if (!value) {
        return Promise.reject('请输入手机号');
      }
      if (/^1[0-9]{10}$/.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请输入合法的手机号');
      }
    }
    // 注册表单检验
    const registerRules = {
      email: [
        { required: true, validator: checkEmail, trigger: 'blur' },
      ],
      mobile: [
        { required: true, validator: checkMobile, trigger: ['blur', 'change'] },
      ],
      username: [
        { required: true, message: '请输入昵称', trigger: 'blur'},
        { min: 1, max: 8, message: '昵称长度在5-10个字直接', trigger: "blur"}
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur'},
      ],
      code: [
        { required: true, message: '请输入短信验证码', trigger: 'blur'},
      ],
      sex: [
        { required: true, message: '请选择性别', trigger: 'blur'},
      ]
    }


    // 点击登录按钮
    const onSubmit = () => {
      // 判断表单是否填写
      if (!loginForm.mobile || !loginForm.password || !loginForm.captcha) {
        message.warning('请填写登录相关信息')
        return;
      }
      // 校验手机号是否合法
      const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;    //11位手机号码正则
      if (!regTel.test(loginForm.mobile)) {
        message.warning('请输入合法的手机号')
        return;
      } else {
        // 手机号正确
        // const formdata = new FormData()
        // formdata.append('mobile', loginForm.mobile)
        // formdata.append('password', loginForm.password)
        // formdata.append('captcha', loginForm.captcha)
        // formdata.append('type', loginForm.type)
          apiUserLogin(loginForm).then((res)=>{
          // console.log('结果：', res)
          if (res.data.code !== 200) {
            message.warning(res.data.msg)
            return
          } else {
            // 登录成功，获取人员信息，并跳转页面
            message.success('登录成功')
            // router.push('/overview')
              // 获取登录人员信息
              apiGetUserInfo({}).then((res) => {
                  console.log('人员信息为', res.data)
                  if (res.data.code == 200) {
                      const user = JSON.stringify(res.data.data)
                      window.localStorage.setItem('user', user)
                      router.push('/overview')
                  }
              })
          }
        }).catch((err)=>{
          console.log(err)
        })
      }

    }

    // 手机验证码登录
      const codeLogin = () => {
        // 判断表单是否填写
          if (!codeForm.mobile || !codeForm.ssmCode) {
              message.warning('请填写相关信息')
              return
          }
          // 校验手机号是否合法
          const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;    //11位手机号码正则
          if (!regTel.test(codeForm.mobile)) {
              message.warning('请输入合法的手机号')
              return;
          } else {
                apiUserLogin(codeForm).then((res) => {
                    console.log('结果', res)
                })
          }
      }

    // 点击重置按钮
    const reset = () => {

    }

    // 重置手机验证码登录表单
      const resetCodeForm = () => {

      }

    // 跳转到注册页面
    const toRegister = () => {
      state.status = 2
      // registerRef.value.resetFields();
    }

    // 点击注册按钮
    const register = () => {
      // 先检验表单是否填写
      registerRef.value
        .validate()
        .then( async ()=> {
          // 验证通过，调用 注册 接口
          // const data = await userRegister(registerForm)
          // console.log('注册结果：', data)
            apiUserRegister(registerForm).then((res)=>{
            console.log(1111, res)
            if (res.data.code === 200) {
              message.success(res.data.msg)
              // 清空信息
              registerRef.value.resetFields();
              state.status = 1
            } else {
              message.error(res.data.msg)
            }
          }).catch((err) => {
            console.log(22222, err)
          }).finally((el) => {
            console.log(333, el)
          })

        })
    }

    // 跳转到登录页面
    const toLogin = () => {
      state.status = 1
    }

    // 获取手机验证码
    const getCode = async () => {
      // 首先判断手机号存不存在
      if (!registerForm.mobile) {
        message.warning('请输入手机号')
        return
      }
      state.codeLoading = true
      if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(registerForm.mobile))) {
        const params = {
          mobile: registerForm.mobile,
          sms_code_method: 'home_register_sms_code'
        }
        await apiGetUserCode(params)
        state.codeLoading = false
      } else {
        message.warning('请输入合法的手机号')
        state.codeLoading = false
        return
      }

    }

    // 登录时获取验证码
      const getLoginCode = async () => {
          // 首先判断手机号存不存在
          if (!codeForm.mobile) {
              message.warning('请输入手机号')
              return
          }
          state.codeLoading = true
          if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(codeForm.mobile))) {
              const params = {
                  mobile: codeForm.mobile,
                  sms_code_method: 'home_login_sms_code'
              }
              await apiGetUserCode(params)
              state.codeLoading = false
          } else {
              message.warning('请输入合法的手机号')
              state.codeLoading = false
              return
          }
      }

    // 重置注册表单
    const resetRegister = () => {
      registerRef.value.resetFields();
    }

    // 获取图片验证码
    const getCaptcha = () => {
        apiGetUserImgCode({}).then((res)=> {
        console.log('结果是：', res)
        // state.imgUrl = res.data
        state.imgUrl = `data: image/jpeg;base64,${btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
      })
    }

    // 获取当前时间
    const getTime = () => {
      state.timeTimer = setInterval(() => {
        state.time = dateFormat(new Date(),'hh:mm:ss');
        state.date = dateFormat(new Date(),'yyyy年MM月dd日');
      }, 1000);
    }

    // 点击验证码刷新验证码
    const refreshCode = () => {
      getCaptcha()
    }

    onMounted(()=>{
      getTime()
      getCaptcha()
    })

    onUnmounted(()=>{
      clearInterval(state.timeTimer)
    })

    return{
      loginRef,
      registerRef,
        codeFormRef,
      registerForm,
      loginForm,
        codeForm,
      ...toRefs(state),
      registerRules,
      labelCol: { span: 5 },
      wrapperCol: { span: 24 },
      onSubmit,
      reset,
      toRegister,
      register,
      toLogin,
      getCode,
      resetRegister,
      refreshCode,
        getLoginCode,
        codeLogin,
        resetCodeForm
    }
  }
})
</script>

<style lang="less" scoped>
.login{
  width: 100%;
  height: 100%;

.content{
  height: 100%;
  //background: url("../../assets/img/userLogin/bg.jpeg") no-repeat;
  //  display: flex;

    .left {
        width: 100%;
        height: 100%;

        img{
            width: 100%;
            height: 100%;
        }
    }

    .form {
        position: absolute;
        top: 20%;
        left: 20%;

        .code {
            display: flex;
            .captcha{
                width: 150px;
                height: auto;
                //background: green;
            }
        }
    }

    .time {
        position: absolute;
        top: 5%;
        left: 5%;
        font-size: 20px;
    }
    }
}
::v-deep .ant-radio-group {
  float: left;
}
</style>
